import lodash from 'lodash'
import pathToRegexp from 'path-to-regexp'
import axios from './interceptors'
import { Loading, Message } from 'element-ui'

axios.defaults.headers.post['Content-Type'] = 'application/json'
axios.defaults.withCredentials = true

const fetch = (options) => {
  /* eslint-disable */
  let { method = 'get', data, url, timeout = 0 } = options
  const cloneData = lodash.cloneDeep(data)
  try {
    let domin = ''
    if (url.match(/[a-zA-z]+:\/\/[^/]*/)) {
      domin = url.match(/[a-zA-z]+:\/\/[^/]*/)[0]
      url = url.slice(domin.length)
    }
    const match = pathToRegexp.parse(url)
    url = pathToRegexp.compile(url)(data)
    for (let item of match) {
      if (item instanceof Object && item.name in cloneData) {
        delete cloneData[item.name]
      }
    }
    url = domin + url
  } catch (e) {
    console.log(e)
  }

  switch (method.toLowerCase()) {
    case 'get':
      return axios.get(url, {
        params: cloneData,
        timeout,
      })
    case 'delete':
      return axios.delete(url, {
        data: cloneData,
      })
    case 'post':
      return axios.post(url, cloneData)
    case 'put':
      return axios.put(url, cloneData)
    case 'patch':
      return axios.patch(url, cloneData)
    default:
      return axios(options)
  }
}

export default function request(options) {
  let loading = Loading.service({
    background: 'rgba(0, 0, 0, 0.3)',
    fullscreen: true
  })
  return fetch(options)
    .then((response) => {
      loading.close()
      const { statusText, status } = response
      const data = response.data
      var statusCode = data.statusCode
      if ('200' !== statusCode) {
        Message({
          type: 'error',
          message: data.errMsg || '系统错误'
        })
      }
      return {
        success: true,
        message: statusText,
        statusCode,
        ...data,
      }
    })
    .catch((error) => {
      loading.close()
      Message({
        type: 'error',
        message: error.errMsg || '系统错误'
      })
      const { response } = error
      let msg
      let statusCode
      if (response && response instanceof Object) {
        const { data, statusText } = response
        statusCode = response.status
        msg = data.message || statusText
      } else {
        statusCode = 600
        msg = error.message || 'Network Error'
      }
      return { success: false, statusCode, message: msg }
    })
}
